package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
)

// runInteractiveClient 建立 TCP 连接后，允许用户在终端输入命令。
func runInteractiveClient() error {
	conn, err := net.Dial("tcp", "127.0.0.1:9090") // 三次握手在 Dial 内部完成
	if err != nil {
		return fmt.Errorf("dial server: %w", err)
	}
	defer conn.Close()

	fmt.Println("[client] connected to server. Try commands: PING / TIME / any text / QUIT")

	reader := bufio.NewReader(os.Stdin)
	serverReader := bufio.NewReader(conn)

	for {
		fmt.Print("> ")
		text, err := reader.ReadString('\n')
		if err != nil {
			return fmt.Errorf("read stdin: %w", err)
		}

		if _, err := conn.Write([]byte(text)); err != nil {
			return fmt.Errorf("write to server: %w", err)
		}

		reply, err := serverReader.ReadString('\n')
		if err != nil {
			return fmt.Errorf("read reply: %w", err)
		}

		fmt.Printf("[client] reply: %s", reply)

		if reply == "BYE\n" {
			return nil
		}
	}
}

func main() {
	if err := runInteractiveClient(); err != nil {
		fmt.Println("client error:", err)
	}
}
